import { useLoginApi } from '@/api/login-api';
import { useUserApi } from '@/api/user-api';
import { AppComstants, RStatus } from '@/common/comstants';
import router from '@/router';
import { appLocalStorage } from '@/utils/storage-util';
import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
  }),
  actions: {
    /**登录 */
    async login(params) {
      const res = await useLoginApi().login(params);
      if (res.status === RStatus.SUCCESS) {
        ElMessage.success(res.message);
        appLocalStorage.setItem(AppComstants.Token, res.data.access_token);
        await this.updateUserInfo();
      } else {
        ElMessage.error(res.message);
      }
    },
    /**更新用户信息 */
    async updateUserInfo() {
      if (this.userInfo) {
        return;
      }

      if (appLocalStorage.getItem(AppComstants.USER_INFO)) {
        this.userInfo = appLocalStorage.getItem(AppComstants.USER_INFO);
      }

      const res = await useUserApi().getUserInfo();
      if (res.status === RStatus.SUCCESS) {
        appLocalStorage.setItem(AppComstants.USER_INFO, res.data);
        this.userInfo = res.data;
      }
    },
    /**退出登录 */
    logout() {
      ElMessageBox.confirm('确定退出登录？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }).then(() => {
        appLocalStorage.clear();
        this.userInfo = null;
        router.replace('/login');
      });
    },
  },
});
